package com.slz3.business.menu;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.slz3.business.frame.util.UUIDUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class GenerateMenuData {

    public static String menuBaseSql = "insert into system_management.sys_menu" +
            "(uuid, create_time, valid_flag, ser_audit, ser_code, " +
            "ser_ico, ser_memo, ser_name, ser_num, ser_uri, " +
            "ser_using, parent_id, increment_id)values\n";
    public static String menuColumnSql = "('%s', current_timestamp, 'VALID', 'WAIT_SUBMIT', '%s', " +
            "'%s', '%s', '%s', '%s', '%s', " +
            "'ENABLE', %s, '%s'),\n";
    public static String permissionsBaseSql = "insert into system_management.sys_permissions(uuid, create_time, valid_flag, ser_audit, ser_memo, ser_num, ser_using, menu_uuid, ser_uri)values\n";
    public static String permissionsColumnSql = "('%s', current_timestamp, 'VALID', 'WAIT_SUBMIT', '%s', '%s', 'ENABLE', '%s', '%s'),\n";
    public static String roleMenuBaseSql = "INSERT INTO system_management.sys_role_menu (uuid, create_time, creator, creator_ip, last_modifier, last_modifier_ip, last_modify_time, owner_organize, owner_role, upper, valid_flag, menu_uuid, role_uuid) VALUES \n";
    public static String roleMenuColumnSql = "('%s', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'VALID', '%s', 'a7923690-1d7b-4d3a-8502-4e0627a66af3'),\n";
    public static String rolePermissionsBaseSql = "INSERT INTO system_management.sys_role_permissions (uuid, create_time, creator, creator_ip, last_modifier, last_modifier_ip, last_modify_time, owner_organize, owner_role, upper, valid_flag, menu_uuid, permission_uuid, role_uuid, ser_audit, ser_using) VALUES \n";
    public static String rolePermissionsColumnSql = "('%s', '2018-11-05 16:25:37.134', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'VALID', '%s', '%s', 'a7923690-1d7b-4d3a-8502-4e0627a66af3', 'WAIT_SUBMIT', 'ENABLE'), \n";

    /*


     */

    public static StringBuilder menuSb = new StringBuilder();
    public static StringBuilder permissionsSb = new StringBuilder();
    public static StringBuilder roleMenuSb = new StringBuilder();
    public static StringBuilder rolePermissionsSb = new StringBuilder();
    public static AtomicLong atomicLong = new AtomicLong();
    public static void main(String[] args) throws Exception {
        Gson gson = new Gson();
        File file = new File(GenerateMenuData.class.getResource("/menu.json").getFile());
        List<MenuBean> menuBeanList = gson.fromJson(FileUtils.readFileToString(file, "utf8"), new TypeToken<List<MenuBean>>(){}.getType());
        menuSb.append(menuBaseSql);
        permissionsSb.append(permissionsBaseSql);
        roleMenuSb.append(roleMenuBaseSql);
        rolePermissionsSb.append(rolePermissionsBaseSql);

        Map<String, List<String>> permissionsSbListMap = listAllUrls();
//        for (MenuBean item : menuBeanList){
        for (int i = 0; i < menuBeanList.size(); i ++){
            toDoIt(menuBeanList.get(i), null, permissionsSbListMap, 100000 + i * 50000, 0);
        }
        toDoOtherPermission(permissionsSbListMap);


        int lastIndexOf = menuSb.lastIndexOf(",");
        menuSb.replace(lastIndexOf, lastIndexOf + 1, ";");

        lastIndexOf = permissionsSb.lastIndexOf(",");
        permissionsSb.replace(lastIndexOf, lastIndexOf + 1, ";");

        lastIndexOf = roleMenuSb.lastIndexOf(",");
        roleMenuSb.replace(lastIndexOf, lastIndexOf + 1, ";");

        lastIndexOf = rolePermissionsSb.lastIndexOf(",");
        rolePermissionsSb.replace(lastIndexOf, lastIndexOf + 1, ";");

        System.out.println(menuSb.toString());
        System.out.println(permissionsSb.toString());
        System.out.println(roleMenuSb.toString());
        System.out.println(rolePermissionsSb.toString());
    }

    private static void toDoOtherPermission(Map<String, List<String>> permissionsSbListMap) {
        if (permissionsSbListMap.isEmpty()){
            return;
        }
        for (Map.Entry<String, List<String>> entry : permissionsSbListMap.entrySet()){
            for (String permission : entry.getValue()){
                String[] split = permission.split("/");
                String permissionsId = UUID.randomUUID().toString();
                permissionsSb.append(String.format(String.format(permissionsColumnSql,
                        permissionsId,
                        "-" + getPermission(split[3]),
                        atomicLong.incrementAndGet() + "",
                        "",
                        permission
                )));
                rolePermissionsSb.append(String.format(rolePermissionsColumnSql,
                        UUIDUtils.generateUUID().toString(),
                        "",
                        permissionsId
                ));
            }
        }

    }

    private static void toDoIt(MenuBean menuBean, String parentId,
                               Map<String, List<String>> permissionsSbListMap,
                               int parentMenuId, int childrenMenuId) {
        String menuId = UUIDUtils.generateUUID().toString();
        int menuIncrementId = parentMenuId + childrenMenuId;
        menuSb.append(String.format(menuColumnSql, menuId, menuBean.getId(),
                "pa-icon", menuBean.getName(), menuBean.getName(), menuIncrementId + "", menuBean.getHref(),
                parentId == null ? "NULL" : "\'"+parentId+"\'", menuIncrementId + ""));
        roleMenuSb.append(String.format(roleMenuColumnSql, UUIDUtils.generateUUID().toString(), menuId));
        String id = menuBean.getId();
        String s = id.replace("-", "").toLowerCase();
        List<String> permissionsList = permissionsSbListMap.get(id.replace("-", "").toLowerCase());
        if ("sysRole".equalsIgnoreCase(s)) {
            permissionsList.addAll(permissionsSbListMap.get("sysrolemenu"));
        }

        if (!CollectionUtils.isEmpty(permissionsList)){
            for (String permission : permissionsList){
                String[] split = permission.split("/");
                String permissionsId = UUID.randomUUID().toString();
                permissionsSb.append(String.format(String.format(permissionsColumnSql,
                        permissionsId,
                        menuBean.getName() + "-" + getPermission(split[3]),
                        atomicLong.incrementAndGet() + "",
                        menuId,
                        permission
                    )));
                rolePermissionsSb.append(String.format(rolePermissionsColumnSql,
                        UUIDUtils.generateUUID().toString(),
                        menuId,
                        permissionsId
                ));
            }
            permissionsSbListMap.remove(id.replace("-", "").toLowerCase());
            if ("sysRole".equalsIgnoreCase(s)) {
                permissionsSbListMap.remove("sysrolemenu");
            }
        }
        if (!CollectionUtils.isEmpty(menuBean.getMenus())){
//            for (MenuBean item : menuBean.getMenus()){
            for (int i = 0; i < menuBean.getMenus().size(); i ++){
                toDoIt(menuBean.getMenus().get(i), menuId, permissionsSbListMap, parentMenuId, childrenMenuId + i + 1);
            }
        }
    }

    private static String getPermission(String s) {
        switch (s){
            case "add": return "添加";
            case "delete": return "删除";
            case "modify": return "修改";
            case "audit_submit": return "审核提交";
            case "audit": return "审核";
            case "audit_reject": return "审核拒绝";
            case "using_enable": return "启用";
            case "using_disable": return "禁用";
            case "list": return "列表";
            case "info": return "详情";
            case "login": return "登陆";
            case "logout": return "注销";
            case "register": return "注册";
            case "list_all_menu": return "所有菜单";
            case "list_menu_by_login": return "根据登陆用户列出菜单";
            default:
                return s;
        }
    }

    private static Map<String, List<String>> listAllUrls() throws Exception {
        File file = new File(GenerateMenuData.class.getResource("/permissions.txt").getFile());
        List<String> list = FileUtils.readLines(file, "utf8");
        List<String> urls = new ArrayList<>();
        String prefix = "";
//        ((PUT && /modify/) && Accept: [application/json;charset=UTF-8]) -> com.slz3.business.module.systemManagement.sysMenu.SysMenuRouter$$Lambda$757/1491951315@6f215ff3
//                (GET && /info/) -> com.slz3.business.module.systemManagement.sysMenu.SysMenuRouter$$Lambda$758/322860937@6066cf5
//                (GET && /list/) -> com.slz3.business.module.systemManagement.sysMenu.SysMenuRouter$$Lambda$759/1660189868@3d63becf
//                (GET && /listAllMenu/) -
//
        Pattern startPattern = Pattern.compile("^(.*?) => \\{$");
        Pattern subPattern = Pattern.compile("^.*? && (.*?)\\) .*$");
        for (String line : list) {
            if ("}".equalsIgnoreCase(line)){
                prefix = "";
                continue;
            }
            Matcher startMacher = startPattern.matcher(line);
            if (startMacher.matches()){
                prefix = startMacher.group(1);
                continue;
            }
            Matcher matcher = subPattern.matcher(line);
            if (matcher.matches()){
                urls.add(prefix + matcher.group(1));
                continue;
            }
        }
        return urls.stream().filter(item -> item.split("/").length == 4)
                .collect(Collectors.groupingBy(
                        (item) -> item.split("/")[2].toLowerCase(), Collectors.toList()
                ));
    }
}
